#include "ActionManager.h"
#include "..\utils\Log.h"

namespace ds {

ActionManager::ActionManager() {
}


ActionManager::~ActionManager() {
	Actions::iterator it = m_Actions.begin();
	while ( it != m_Actions.end() ) {
		delete (*it);
		it = m_Actions.erase(it);
	}
}

void ActionManager::addAction(Action* action) {
	m_Actions.push_back(action);
}

void ActionManager::startAction(const std::string& name) {	
	Action* act = findAction(name);
	if ( act != 0 ) {
		LOGC(logINFO,"ActionManager") << "starting action " << name;
		act->start();
		m_ActiveActions.push_back(act);
	}
}

void ActionManager::stopAction(const std::string& name) {
	Action* act = findAction(name);
	if ( act != 0 ) {
		LOGC(logINFO,"ActionManager") << "stopping action " << name;
		act->stop();
		act->setActive(false);
	}
}

void ActionManager::update(float elapsed) {
	Actions::iterator it = m_ActiveActions.begin();
	while ( it != m_ActiveActions.end() ) {
		if ( (*it)->isActive() ) {
			(*it)->update(elapsed);
		}
		if ( !(*it)->isActive() ) {
			LOGC(logINFO,"ActionManager") << "action " << (*it)->getName() << " has finished - removing from active actions";
			it = m_ActiveActions.erase(it);
		}
		else {
			++it;
		}
	}
}

Action* ActionManager::findAction(const std::string& name) {
	LOGC(logINFO,"ActionManager") << "looking for action " << name;
	for ( size_t i = 0 ; i < m_Actions.size(); ++i ) {
		if ( m_Actions[i]->getName() == name ) {
			LOGC(logINFO,"ActionManager") << "found action";
			return m_Actions[i];
		}
	}
	return 0;
}

void ActionManager::debug() {	
	LOGC(logINFO,"ActionManager") << "Registered actions";
	for ( size_t i = 0 ; i < m_Actions.size(); ++i ) {
		LOGC(logINFO,"ActionManager") << m_Actions[i]->getName();
	}
	LOGC(logINFO,"ActionManager") << "Active actions";
	for ( size_t i = 0 ; i < m_ActiveActions.size(); ++i ) {
		LOGC(logINFO,"ActionManager") << m_ActiveActions[i]->getName();
	}
}

}
